using Digitalmes.Application.Services;
using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.Products.Commands;

/// <summary>
/// 产品让步接收命令。
/// </summary>
/// <param name="Id">产品状态 Id</param>
/// <param name="IsCompleted">是否完工</param>
public sealed record ConcedeProductCommand(long Id, bool IsCompleted) : IRequest<IResult<bool>>;

internal sealed class ConcedeProductCommandHandler(IRepository<ProdCurrentState> repo, IWorkOrderService workOrderService) : IRequestHandler<ConcedeProductCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(ConcedeProductCommand request, CancellationToken cancellationToken)
    {
        var currentState = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (currentState == null)
        {
            return Result.Failure("未找到要更新的产品");
        }

        if (currentState.Status is not PassEnum.NG and not PassEnum.ForceNG)
        {
            return Result.Failure("产品只有在 NG 状态下才能让步接收");
        }

        // 已开返工单的产品不能让步接收
        if (currentState.InReworkDocId > 0)
        {
            return Result.Failure("已开返工单的产品不能让步接收");
        }

        currentState.Status = PassEnum.ForceOK;
        var ok = await repo.UpdateAsync(currentState, m => new
        {
            m.Status,
        }, cancellationToken);

        // 更新工单下线数量
        if (ok && request.IsCompleted && !string.IsNullOrEmpty(currentState.Wo))
        {
            await workOrderService.IncrementGoodQtyAsync(currentState.Wo, cancellationToken);
        }

        return Result.From(ok);
    }
}
